package com.example.qxfw.dzzh.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.yj.AridWarnAnalysisFile;
import com.example.qxfw.common.entity.yj.DzWarning;
import com.example.qxfw.common.entity.yj.DzWarningTemp;
import com.example.qxfw.dzzh.dto.SurfaceDto;
import com.example.qxfw.dzzh.service.AridWarnAnalysisFileService;
import com.example.qxfw.dzzh.service.DqyjService;
import com.example.qxfw.dzzh.service.DzWarningService;
import com.example.qxfw.dzzh.service.DzWarningTempService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Api(tags = "地质灾害-短期预警")
@RestController
@CrossOrigin
@RequestMapping("/dqyj")
public class DqyjController {

    @Value("${filePath.active}")
    private String active;

    @Autowired
    private AridWarnAnalysisFileService aridWarnAnalysisFileService;

    @Autowired
    private DzWarningService dzWarningService;

    @Autowired
    private DzWarningTempService dzWarningTempService;

    @Autowired
    private DqyjService dqyjService;

    @ApiOperation("获取地灾预警分析格点文件信息")
    @GetMapping("/getPgFile")
    public SysResult getPgFile(String type, String fileName) {
        List<AridWarnAnalysisFile> aridWarnAnalysisFiles = aridWarnAnalysisFileService.listByParam1(type, fileName);
        return SysResult.success(aridWarnAnalysisFiles.get(0));
    }

    @ApiOperation("获取地灾预警分析格点文件")
    @GetMapping("/getAridWarnAnalysisFile")
    public SysResult getAridWarnAnalysisFile(String dateChar, String type, String fileName, String city) {
        List<AridWarnAnalysisFile> aridWarnAnalysisFiles = aridWarnAnalysisFileService.listByParam(dateChar, type, fileName, city);
        return SysResult.success(aridWarnAnalysisFiles);
    }

    @ApiOperation("保存地灾预警分析格点文件")
    @RequestMapping("/saveAridWarnAnalysisFile")
    public SysResult saveAridWarnAnalysisFile(@RequestBody AridWarnAnalysisFile aridWarnAnalysisFile) {
        AridWarnAnalysisFile save = aridWarnAnalysisFileService.save(aridWarnAnalysisFile);
        return SysResult.success(save);
    }

    @ApiOperation("查询地灾预警信息")
    @RequestMapping("/getDzWarning")
    public SysResult getDzWarning(Integer id, String dateChar, String timeChar, String warningType) {
        List<DzWarning> dzWarnings = dzWarningService.listByParam(id, dateChar, timeChar, warningType);
        return SysResult.success(dzWarnings);
    }

    @ApiOperation("更新地灾预警")
    @RequestMapping("/updateDzWarning")
    public SysResult updateDzWarning(@RequestBody DzWarning dzWarning) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int rows = dzWarningService.update(dzWarning);
        if (rows == 0)
            return SysResult.success();
        List<DzWarning> dzWarnings = dzWarningService.listByParam(null, sdf.format(dzWarning.getDatechar()), null, dzWarning.getWarningtype());
        return SysResult.success(dzWarnings);
    }

    @ApiOperation("用id更新地灾预警")
    @RequestMapping("updateDzWarningById")
    public SysResult updateDzWarningById(@RequestBody DzWarning dzWarning) {
        DzWarning dzWarning1 = dzWarningService.updateById(dzWarning);
        return SysResult.success(dzWarning1);
    }

    @ApiOperation("保存地灾预警")
    @RequestMapping("/saveDzWarning")
    public SysResult saveDzWarning(@RequestBody DzWarning dzWarning) {
        DzWarning dzWarning1 = dzWarningService.save(dzWarning);
        return SysResult.success(dzWarning1);
    }

    @ApiOperation("保存地灾预警操作记录")
    @RequestMapping("/saveDzWarningTemp")
    public SysResult saveDzWarningTemp(@RequestBody DzWarningTemp dzWarningTemp) {
        DzWarningTemp save = dzWarningTempService.save(dzWarningTemp);
        return SysResult.success(save);
    }


    @ApiOperation("test")
    @RequestMapping("/getArea")
    public SysResult getArea() throws IOException {
        List area = dqyjService.getArea();
        return SysResult.success(area);
    }

    @ApiOperation("test2")
    @GetMapping("/getSurface")
    public SysResult getSurface() throws IOException {
        List<SurfaceDto> area1 = dqyjService.getArea1();
        return SysResult.success(area1);
    }

    @ApiOperation("获取地灾因子")
    @RequestMapping("/creatTxt")
    public SysResult creatTxt(String index) throws IOException {
        String filePath = dqyjService.createTxt(index);
        return SysResult.success(filePath);
    }

    @ApiOperation("获取产品模板")
    @GetMapping("/getTemplate")
    public Object getTemplate() {
        //模板路径
        String templatePath;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        if (active.equals("dev")) {
            templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                    "\\src\\main\\resources\\Documents\\风险预警模板\\地质灾害气象风险预警模板.docx";
        } else {
            templatePath = applicationHome.getSource().getParentFile() +
                    "\\resource\\Documents\\风险预警模板\\地质灾害气象风险预警模板.docx";
        }
        // 设置前端响应
        byte[] buffer = new byte[1024];
        int bytesRead;
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                FileInputStream inputStream = new FileInputStream(templatePath);
        ) {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", "地灾预警文档模板.docx");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("模板下载失败");
        }
        return null;
    }

    @ApiOperation("获取产品最新期数")
    @GetMapping("getMaxId")
    public SysResult getMaxId() {
        Integer maxId = dqyjService.getMaxId();
        return SysResult.success(maxId);
    }

    @ApiOperation("生成产品")
    @PostMapping("/createProduct")
    public Object createProduct(
            Integer issueNum,
            String userName,
            String yjType,
            String sXType,
            String date,
            String timeChar,
            Integer nTimes,
            String colorAndPos,
            String posStr,
            MultipartFile[] images,
            String layerName,
            String dlData) throws IOException, NoSuchFieldException, IllegalAccessException, ParseException {
        return dqyjService.createProduct(issueNum, userName, yjType, sXType, date, timeChar, nTimes, colorAndPos, posStr, images, layerName, dlData);
    }

}
